// JavaScript Document

//var serverIp = "http://10.101.1.177";
//var serverIp = "http://118.123.173.86";
//var serverIp = "http://10.101.1.119";
//var serverIp = "http://192.168.102.198";
//var serverIp = "http://postmsg.cn";
var serverIp = "http://127.0.0.1";
//var serverIp = "http://171.221.173.155";

var serverPort = 8000;
var serverUrl = serverIp + ":" + serverPort;

var P = new PublicModel();
Function.prototype.txtContent = function(){ 
	var _str = this.toString(), 
	s_pos = _str.indexOf("/*")+2, 
	e_pos = _str.lastIndexOf("*/"); 
	return (s_pos<0 || e_pos<0) ? "" : _str.substring(s_pos, e_pos); 
};

/* 通用函数封装，兼容老版本 */
function PublicModel(){
	var $this = this;
	this.getLastMonth = function(){
        var _date = new Date(), y = _date.getFullYear(), m = _date.getMonth() + 1;
        if(m==1){ y = y - 1; m = 13; }
        m--;
        return y + "-" + (m>9 ? m : ("0"+m));
	};
    this.getRecentMonth = function(month){
        var _date = new Date(), y = _date.getFullYear(), m = _date.getMonth() + 1 - month;
        if(m<1){ y = y - 1; m += 12; }
        return y + "-" + (m>9 ? m : ("0"+m));
		}; 
    /* 获取最近几月日期区间 - 截止今天 */
    this.getRecentMonthDate = function(month){ 
        var mDate = $this.getRecentMonth(month), sp = mDate.split("-");
        return {'dateStart': sp[0] + '-' + sp[1] + '-1',
            'dateEnd':$this.DateF(new Date()) }
    };   
    this.getDateByMonth = function(date){ var sp = date.split("-");
        return {'dateStart': sp[0] + '-' + sp[1] + '-1',
            'dateEnd': sp[0] + '-' + sp[1] + '-' + (new Date(parseInt(sp[0]), parseInt(sp[1]),0)).getDate()}
    };
	this.getLastMonthDate = function(){
		return $this.getDateByMonth($this.getLastMonth());
	};

	this.getQueryString = function(name){
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    };
    
    this.range = function(_min, _max){ var rt=[]; for(var i=_min;i<_max;i++)rt.push(i); return rt; };
    this.values = function(obj){ return Object.keys(obj).map(function(k){ return obj[k]; })};
    this.items = function(obj){ return Object.keys(obj).map(function(k){ return [k, obj[k]]; })};

    this.GetMonthNow = function(){ return  new Date().format("yyyy-MM"); };
    
    this.DateF = function(date, _sp) { var sp = "-" || _sp; return [date.getFullYear(), date.getMonth()+1, date.getDate()].join(sp); };
    this.DateDTS = function(date) { return date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds(); };
    this.DateDTM = function(date) { return date.getHours() * 60 + date.getMinutes(); };
    this.DateSTM = function(str){ var sp = str.split(" ")[1].split(":"); return parseInt(sp[0]) * 60 + parseInt(sp[1]); };
    this.DateSTD = function(str){ var sp = str.split(/-| |:/); return new Date(parseInt(sp[0]), parseInt(sp[1]), parseInt(sp[2]),
        parseInt(sp[3]), parseInt(sp[4]), parseInt(sp[5])); };
    this.DateDSTD = function(str){ var sp = str.split(/-| |:/); return new Date(parseInt(sp[0]), parseInt(sp[1])-1, parseInt(sp[2])); };
    this.DateSTDS = function(str){ return str.split(" ")[0]; };
    this.TimeT = function(str){ var sp = str.split(":"); return new Date(0, 0, 0, parseInt(sp[0]), parseInt(sp[1]), 0); };
    this.TimeF = function(date){ return date.getHours() + ":" + date.getMinutes(); };
    this.TimeFormat = function(str){ var sp = str.split(":"); return format0(sp[0]) + ":" + format0(sp[1]) + ":" + format0(sp[2]);  };
    this.TimeSTM = function(str){ var sp = str.split(":"); return parseInt(sp[0]) * 60 + parseInt(sp[1]); };
    this.TimeMTS = function(m){
        var h = parseInt(m/60), m = parseInt(m % 60), tm = h + ":" + (m>9 ? m : ("0" + m));
        return m<0 || h>24 ? "" : tm;
    };
    this.format0 = function(m){ return (parseInt(m)>9 ? m : ("0" + m));	};


	//-------------------------------------------cookie相关-----------------------------------------------
    this.setCookie = function(name,value, hour)
    {
        hour = hour || 2;
        var exp = new Date();
        exp.setTime(exp.getTime() + hour * 60*60*1000);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    };
    this.getCookie = function(name)
    {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
        if(arr=document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    };
    this.GetCookie = function(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    };
    this.delCookie = function(name)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!=null)
            document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    };

    //限制文本框数字
    this.LimitInput = function(obj){
        if(obj.value.length==1){obj.value=obj.value.replace(/[^0-9]/g,'')}else{
            obj.value=obj.value.replace(/\D/g,'');
            if(obj.value!="")$(obj).val(parseInt(obj.value));
        }
    };
	
    function format0(m){ return (parseInt(m)>9 ? m : ("0" + m));	}

};



function cout(d){ console.log(d); }

function dictToList(dict){
    return Object.keys(dict).map(function(key){ return {
        name:key, value:dict[key]
    }; });
}
    
function getQueryString(name){ return P.getQueryString(name); }

function range(_min, _max){ return P.range(_min, _max); }
function values(obj){ return P.values(obj); }
function items(obj){ return P.items(obj); }
function set(){this.data={};this.keys=[];this.add=function(e){if(!this.data.hasOwnProperty(e))this.keys.push(e);this.data[e]=1;};}
function sets(e){this.data=e?{e:1}:{};this.keys=e?[e]:[];this.add=function(e){if(!this.data.hasOwnProperty(e))this.keys.push(e);this.data[e]=1;};}

function getCookie(name){ return P.getCookie(name); };

function Init3(option, id){
	var myChart = echarts.init(document.getElementById(id), "dark");
	myChart.setOption(option);
	return myChart;
}

function _$(id){ return document.getElementById(id); }

function delConfirm(msg) {
    var msg = "您真的确定要删除此条数据吗？请确认！";
    if (confirm(msg)==true)return true;
    return false;
}


function ajaxData(key, data, _callbackS, _callbackE, _callbackC){
	var cbkf = (parseInt(Math.random() * 1000) + 1000).toString();
	data["session"] = getCookie('session');
	data['user'] = getCookie('username');
	$.ajax({
		type:'GET', url:serverUrl + '/' + key + '/',
		data:data, dataType:'jsonp', jsonpCallback: 'call1back' + cbkf + 'a',
		crossDomain: true, traditional:true,
		success:function(data)
		{
			if(_callbackS)_callbackS(data);
			if(data.error!=undefined){
				if(data.error && data.errNum==1){
					hideLoading();
					alert("当前用户权限不够，请联系管理员！");
				}
			}
		},
		error:function(data)
		{
			if(_callbackE)_callbackE(data);
			alert("error");
		},
		complete:function(data)
		{
			if(_callbackC)_callbackC(data);
		}
	});
}


function showLoading(){
	var div = "<div id='inline_content' style='padding:0px; background:#fff; border:0px'>" +
		"<img src='../img/loading.gif' width='50'' height='50' />" + "</div>";
	$.colorbox({
		html: div, overlayClose: false, escKey: false, closeButton: false, inline: false, opacity: 0.8, speed: 0,
		onComplete: function () {
			$("#cboxWrapper").css("border", "0px solid #bbb");
			$("#cboxWrapper").css("background-color", "#fff");
		}
	});
}
function hideLoading(){
	// $.colorbox.close();
}
function refresh(){
	window.location.reload();
}

// 菜单效果
function loadReady(){
  $(".navbar-expand-toggle").click(function() {
    $(".app-container").toggleClass("expanded");
    return $(".navbar-expand-toggle").toggleClass("fa-rotate-90");
  });
  return $(".navbar-right-expand-toggle").click(function() {
    $(".navbar-right").toggleClass("expanded");
    return $(".navbar-right-expand-toggle").toggleClass("fa-rotate-90");
  });

}

function loadCtlBase($scope){
    $scope.loadReady = loadReady;
}

// angular
function FinishRenderFilters($timeout) {
    return {
        restrict: 'A',
        link: function ($scope, element, attr) {
            if ($scope.$last !== true)return;
            $timeout(function () {
                $('.date').datetimepicker({
                    format: 'yyyy-mm-dd', language:'zh-CN', autoclose:true, minView:"month"
                });            
             });
        }
    }
}
//---------------------------------一般通用函数--------------------------------------------------


function ajaxToInput(key, data, viewId){
	var url = serverUrl + '/' + key + '/';
	var div = $("<div style='display: none'></div>");
	var form = $('<form action="' + url + '" method="post"></form>');
	data['userId'] = getCookie('username');
	for(var k in data){
		var ipt = $("<input type='text' name='"+ k +"' value="+ "'' />");
		form.append(ipt);
		ipt.val(data[k].toString().replace(/"/g, "'"));
	}

	div.append(form);
	$("#"+viewId).append(div);
	form.submit();
}


function checkLogin(){
	var session = getCookie('session'), userName = getCookie('username'),
		nickName = getCookie('nickname'), level = getCookie('level'), unitName = getCookie('unitname') || '';
	if(level!=null)level = parseInt(level);
	if(!session || !userName || !level){
		window.location.href="login.html";
	}else{
		$('#u_username').html(userName);
        $('#u_username1').html(userName);
		$('#u_nickname').html(nickName);
		$('#u_unitname').html(unitName);
		$('#u_level').html('lv '+ level);
        var levels = getGroups().levels; 
		$('#u_lvname').html(levels[level].name);
        checkLevel(level);
	}
}
function quit(){
    P.delCookie('level');
    P.delCookie('session');
    P.delCookie('username');
	window.location.href="login.html";
    //// 若有时间，可写登录日志
}

function checkLevel(lv){ 
    if(lv<4){
        $(document).ready(function(){
            $("#adminMenu").remove();   
        });  
        
    }
}

//// 用户组对应信息
function getGroups(){
    var Groups = [
        {'name':'冻结用户', 'color':'#777', 'level':-1}, {'name':'一般会员', 'color':'#5bc0de', 'level':1},
        {'name':'高级会员', 'color':'#5cb85c', 'level':2},  //{'name':'高级会员', 'color':'#f0ad4e', 'level':3},
         {'name':'辅助管理员', 'color':'#f0ad4e', 'level':4},
        {'name':'超级管理员', 'color':'#d9534f', 'level':5}
        //#777 #5bc0de #5cb85c f0ad4e #d9534f    //primary   #337ab7
    ];
    var levels = Groups.reduce(function(a, b){ a[b.level] = b; return a; }, {});
    return { groups: Groups, levels: levels}
}

function getLevelText(l){
    return getGroups().levels[l].name;
}

Date.prototype.format = function(fmt) {
	var o = {
		"M+" : this.getMonth()+1,                 //月份
		"d+" : this.getDate(),                    //日
		"h+" : this.getHours(),                   //小时
		"m+" : this.getMinutes(),                 //分
		"s+" : this.getSeconds(),                 //秒
		"q+" : Math.floor((this.getMonth()+3)/3), //季度
		"S"  : this.getMilliseconds()             //毫秒
	};
	if(/(y+)/.test(fmt)) { fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); }
	for(var k in o) {
		if(new RegExp("("+ k +")").test(fmt)){ fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); }
	}
	return fmt;
};

function getObjValue(obj, key){
	return (key in obj) ? obj[key] : null;
}
